package com.htbb.service.carInsure.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.htbb.common.base.MappingConfig;
import com.htbb.common.base.PropertiesConfig;
import com.htbb.common.util.CheckIdCardUtils;
import com.htbb.common.util.StringUtil;
import com.htbb.model.carInsure.CoverageDto;
import com.htbb.model.carInsure.ReqOfCarIsu;
import com.htbb.model.personalInsure.dto.Channel;
import com.htbb.model.personalInsure.entity.CheckInfo;
import com.htbb.order.entity.CarOrder;
import com.htbb.order.entity.Product;
import com.htbb.order.entity.SysCarInsure;
import com.htbb.order.entity.TcCar;
import com.htbb.order.entity.TcCarInsDetail;
import com.htbb.order.entity.TcIsu;
import com.htbb.order.entity.TcOrder;
import com.htbb.order.enums.IsuStatus;
import com.htbb.order.enums.OrderStatus;
import com.htbb.order.interfaces.SysCarInsureService;
import com.htbb.order.interfaces.TcCarInsDetailService;
import com.htbb.order.interfaces.TcCarService;
import com.htbb.order.interfaces.TcIsuService;
import com.htbb.order.interfaces.TcOrderService;
import com.htbb.order.utils.DateUtil;
import com.htbb.pay.entity.TcPay;
import com.htbb.pay.interfaces.TcPayService;
import com.htbb.product.exception.ExcpProductNotExist;
import com.htbb.product.interfaces.SysProductService;
import com.htbb.service.carInsure.TcCarInsureService;


/**
* @author lll
* @date 2017-5-23 
* @Description:车辆信息service接口实现层
*/
@Service
public class TcCarInsureServiceImpl implements TcCarInsureService {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private SysProductService sysProductService;
	@Autowired
	private TcOrderService tcOrderService;
	@Autowired
	private TcIsuService tcIsuService;
	@Autowired
	private TcCarService tcCarService;
	@Autowired
	private TcCarInsDetailService tcCarInsDetailService;
	@Autowired
	private SysCarInsureService sysCarInsureService;
	
	@Override
	public Object carIsuSubmit(ReqOfCarIsu reqOfCarIsu) throws Exception {
		logger.info("<<<<<<<<<<<<<<<<< 车险投保接口  start >>>>>>>>>>>>>>>>>>>");
		
		CheckInfo checkInfo = reqOfCarIsu.check();
		
		TcCar tcCar = reqOfCarIsu.genTcCar();
		
		Map<String,String> amountMap = reqOfCarIsu.getAmountMap();//保障金额
		Map<String,String> freeExceptedsMap = reqOfCarIsu.getFreeExceptedsMap();//不计免赔
		
		List<CoverageDto> coverageDtoList = new LinkedList<CoverageDto>();
		for(String code:reqOfCarIsu.getCoverageCodes().split(",")){
			CoverageDto coverDto = new CoverageDto();
			coverDto.setCoverageCode(code);
			coverDto.setCompensationFreeExcepted(freeExceptedsMap.get(code));
			if("A".equals(code)){//如果为A险
				coverDto.setModecode("0");//损险(A)是否多次事故免赔(0--否/1--是
				coverDto.setLimitAmount(amountMap.get(code));;
			}else if("F".equals(code)){//单独玻璃破碎险
				coverDto.setModecode(reqOfCarIsu.getGlassCode());
				coverDto.setLimitAmount(amountMap.get(code));;
			}else if("C10".equals(code)){//修理期间费用补偿险
				String unitmount = amountMap.get(code);
				coverDto.setQuantity(reqOfCarIsu.getDays());
				coverDto.setLimitAmount(Integer.valueOf(unitmount) * Integer.valueOf(reqOfCarIsu.getDays()) + "");
			}else if("Q4".equals(code)){//指定修理厂险
				coverDto.setLimitAmount(amountMap.get(code));;
			}else{
				if(amountMap.containsKey(code)){
					coverDto.setLimitAmount(amountMap.get(code));
				}
			}
			coverageDtoList.add(coverDto);
		}
		
		Map<String, Object> resultMap =  this.saveOrder(reqOfCarIsu,tcCar,checkInfo,amountMap,freeExceptedsMap,coverageDtoList);
		
		logger.info("<<<<<<<<<<<<<<<<< 车险投保接口  end >>>>>>>>>>>>>>>>>>>");
		return resultMap;
	}
	
	
	/**
	 * 保存车辆信息
	 * @param tcCar
	 * @return
	 * @throws Exception 
	 */
	public Integer saveTcCar(TcCar tcCar) {
		
		int re = 0;
		//根据用户id获取车辆信息
		TcCar entity = new TcCar();
		entity.setLicenseNum(tcCar.getLicenseNum());
		TcCar queryCar = tcCarService.selectByOther(entity);
		if(queryCar == null){
			BeanUtils.copyProperties(entity,tcCar);
			entity.setCreateUser("admin");
			entity.setModifyUser("admin");
			entity.setCarAid(PropertiesConfig.iDCreator.nextId()+"");
			entity.setCarStatus(3);
			re = tcCarService.save(entity);
		}else{
			entity.setCarAid(queryCar.getCarAid());
			re = tcCarService.updateNotNull(entity);
		}
		return re;
	}
	
	/**
	 * 提交订单
	 * @param tcCar
	 * @param checkInfo
	 * @return
	 */
	@Transactional
	public Map<String, Object> saveOrder(ReqOfCarIsu reqOfCarIsu,TcCar tcCar, CheckInfo checkInfo,Map<String,String> amountMap,
			Map<String,String> freeExceptedsMap,List<CoverageDto> coverageDtoList){
		
		Channel channel = MappingConfig.getChannel(reqOfCarIsu.getPartnerCode());
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		long isuAid = PropertiesConfig.iDCreator.nextId();
		long orderAid = PropertiesConfig.iDCreator.nextId();
		long orderDetailAid = PropertiesConfig.iDCreator.nextId();
		long sourceAid = PropertiesConfig.iDCreator.nextId();
		
		this.saveTcCar(tcCar);

		checkInfo.setProid(String.valueOf(PropertiesConfig.CAR_PROD_ID));
		checkInfo.setSkuid(String.valueOf(PropertiesConfig.CAR_PROD_ID));
		
		checkInfo.setIsuAid(String.valueOf(isuAid));
		checkInfo.setOrderAid(String.valueOf(orderAid));
		checkInfo.setCustAid(checkInfo.getOrderAid());
		checkInfo.setOrderDetailAid(String.valueOf(orderDetailAid));
		checkInfo.setSourceAid(String.valueOf(sourceAid));
		checkInfo.setSkuType("CARI");
		checkInfo.setFpCusr("htbb-interface");
		checkInfo.setFpMusr("htbb-interface");
		
		/*查询产品名称*/
		String prodName="";
		try {
			prodName = sysProductService.getProductDetail(PropertiesConfig.CAR_PROD_ID).getProdName();
		} catch (ExcpProductNotExist e1) {
			e1.printStackTrace();
		}
		checkInfo.setProdName(prodName);
		
		TcOrder entity = new TcOrder();
		entity.setChannelTradeId(checkInfo.getChannelTradeId());
		TcOrder tcOrder =  tcOrderService.selectByOther(entity);
		if(tcOrder != null){
			String isuId = tcIsuService.getIsuIdByOrderId(tcOrder.getOrderId());
			resultMap.put("isuAid", isuId);
			resultMap.put("orderAid", tcOrder.getOrderId());
			return resultMap;
		}
		
		/**保存商业保单*/
		checkInfo.setIsuDtStart(checkInfo.getBisuDtStart());
		checkInfo.setIsuDtEnd(checkInfo.getBisuDtEnd());
		
		/**生成订单*/
		this.saveCarInsureOrder(reqOfCarIsu, checkInfo, channel);
		
	    TcCarInsDetail tcCarInsDetail = new TcCarInsDetail();
	    boolean flagsave = false; //是否插入车船税记录
	    
	    SysCarInsure querySysCarInsure = new SysCarInsure();
	    
	    for(CoverageDto coverageDto : coverageDtoList){  //保存保险险种详情
	       querySysCarInsure.setInsCode(coverageDto.getCoverageCode());
		   //根据险别代码获取险种id
	       SysCarInsure sysCarInsure = sysCarInsureService.selectByOther(querySysCarInsure); 
		   
		   //是否投保不计免赔,1：投保不计免赔,2：不投保不计免赔
		   String compensationFreeExcepted = coverageDto.getCompensationFreeExcepted();
		   Integer mianpeiCode = null;
		   if(compensationFreeExcepted != null && !"".equals(compensationFreeExcepted)){
			   mianpeiCode = Integer.parseInt(compensationFreeExcepted);
		   }
		   //自动加入不计分配保险预估
		   if(amountMap.get(coverageDto.getCoverageCode()) == null && coverageDto.getCoverageCode().indexOf("M") == 0){
			   amountMap.put(coverageDto.getCoverageCode(), "0");
		   }
		   //保额预估
		   Long insSumPre = 0L;
		   try{
			   insSumPre = Long.valueOf(Math.round(StringUtil.getTwoFloat(Float.parseFloat(amountMap.get(coverageDto.getCoverageCode())))*100)+"");
		   }catch(Exception e){
			   insSumPre = 0L;
		   }
		   
		   String detailAid = PropertiesConfig.iDCreator.nextId()+"";
		   tcCarInsDetail = new TcCarInsDetail(detailAid, checkInfo.getOrderAid(),checkInfo.getIsuAid(), sysCarInsure.getCarInsAid(),sysCarInsure.getInsName(),
				   String.valueOf(insSumPre), "0",String.valueOf(insSumPre), "0", PropertiesConfig.CAR_COMPANY_NAME,coverageDto.getModecode(),coverageDto.getQuantity());
		   tcCarInsDetail.setMianpeiCode(mianpeiCode);
		   if("BZ".equals(coverageDto.getCoverageCode())){ 
			   tcCarInsDetail.setInsType(2); //交强险
		   }else{
			   tcCarInsDetail.setInsType(1); //交商业险
		   }
		   tcCarInsDetail.setCreateDate(new Date());
		   tcCarInsDetail.setModifyDate(new Date());
		   tcCarInsDetail.setCreateUser("htbb-interface");
		   tcCarInsDetail.setModifyUser("htbb-interface");
		   
		   //保存车险详情信息
		   tcCarInsDetailService.save(tcCarInsDetail);
		   
		   if(!flagsave && "BZ".equals(coverageDto.getCoverageCode())){ //保存车船税
			   querySysCarInsure.setInsCode("BZCCS");
			   //根据险别代码获取险种id
		       sysCarInsure = sysCarInsureService.selectByOther(querySysCarInsure); 
			   
		       detailAid = PropertiesConfig.iDCreator.nextId()+"";
		       tcCarInsDetail.setDetailAid(detailAid);
		       tcCarInsDetail.setCarInsAid(sysCarInsure.getCarInsAid());
		       tcCarInsDetail.setCarInsName(sysCarInsure.getInsName());
			   tcCarInsDetail.setMianpeiCode(mianpeiCode);
			   tcCarInsDetail.setInsType(3); //交车船税
			   tcCarInsDetail.setCreateDate(new Date());
			   tcCarInsDetail.setModifyDate(new Date());
			   //保存车险详情信息
			   tcCarInsDetailService.save(tcCarInsDetail);
			   flagsave = true;
		   }
	    }
		
		resultMap.put("isuAid", checkInfo.getIsuAid());
		resultMap.put("orderAid", checkInfo.getOrderAid());
		
		return resultMap;
	}
	
	/**
	 * 保存车险订单
	 * @param checkInfo
	 * @param channel
	 */
	private TcIsu saveCarInsureOrder(ReqOfCarIsu reqOfCarIsu,CheckInfo checkInfo, Channel channel) {
		Date now = new Date();
		TcOrder tcOrder = new TcOrder();
		tcOrder.setOrderId(checkInfo.getOrderAid());
		tcOrder.setOrderDate(now);
		if(!StringUtils.isEmpty(channel.getIsautopay()) && channel.getIsautopay().equals("1")){
			tcOrder.setOrderStatus(OrderStatus.COMPLETED.getValue());
		}else{
			tcOrder.setOrderStatus(OrderStatus.WAITING_FOR_PAYMENT.getValue());
		}
		
		tcOrder.setOrderPhone(checkInfo.getCustPhone());
		tcOrder.setUserId(checkInfo.getCustAid());
		tcOrder.setUserName(checkInfo.getCustName());
		tcOrder.setProdId(checkInfo.getProid());
		tcOrder.setProdName(checkInfo.getProdName());
		tcOrder.setSkuId(checkInfo.getSkuid());
		tcOrder.setSkuName("车险");
		tcOrder.setProdType("A");
		tcOrder.setProdCode(PropertiesConfig.CAR_SKU_CODE);
		tcOrder.setSkuAmt(Integer.parseInt(checkInfo.getPrice()+""));
		tcOrder.setOrderQty(1);
		tcOrder.setOrderAmt(tcOrder.getSkuAmt());
		tcOrder.setCouponAmt("0");
		tcOrder.setPoint(0);
		tcOrder.setPartnerName(channel.getName()); //订单渠道
		tcOrder.setPartnerId(channel.getPartnerId()); //渠道id
		tcOrder.setGroupName(channel.getName()); //订单总渠道
		tcOrder.setSettlePartnerId(channel.getPartnerId()); //结算渠道编码
		tcOrder.setSettlePartnerName(channel.getName()); //结算渠道名称
		tcOrder.setSettleGroupName(channel.getName()); //订单结算总渠道
		
		TcIsu tcIsu = new TcIsu();
		tcIsu.setIsuId(checkInfo.getIsuAid());
		tcIsu.setOrderId(tcOrder.getOrderId());
		tcIsu.setUserId(tcOrder.getUserId());
		tcIsu.setUserName(tcOrder.getUserName());
		tcIsu.setProdId(tcOrder.getProdId());
		tcIsu.setProdName(tcOrder.getProdName());
		tcIsu.setSkuId(tcOrder.getSkuId());
		tcIsu.setSkuName(tcOrder.getSkuName());
		tcIsu.setProdCode(tcOrder.getProdCode());
		if(!StringUtils.isEmpty(channel.getIsautopay()) && channel.getIsautopay().equals("1")){
			tcIsu.setIsuStatus(IsuStatus.WAITING_FOR_ISSUE.getValue());
		}else{
			tcIsu.setIsuStatus(IsuStatus.WAITING_FOR_PAYMENT.getValue());
		}
		tcIsu.setIsuDate(now);
		tcIsu.setIsuAmt(null); //保额
		tcIsu.setIsuFee(tcOrder.getSkuAmt());
		tcIsu.setIsuNum("");
		tcIsu.setDateStart(DateUtil.parse(checkInfo.getBisuDtStart(), DateUtil.PATTERN_CLASSICAL_SIMPLE));
		tcIsu.setDateEnd(DateUtil.parse(checkInfo.getBisuDtEnd(), DateUtil.PATTERN_CLASSICAL_SIMPLE));
		tcIsu.setCustName(checkInfo.getCustName());
		tcIsu.setCustPhone(checkInfo.getCustPhone());
		tcIsu.setCustSex(CheckIdCardUtils.getSexByIdCard(checkInfo.getCustSsn()));
		tcIsu.setIsuName(checkInfo.getIsuName());
		tcIsu.setIsuPhone(checkInfo.getCustPhone());
		tcIsu.setIsuIdType(1);
		tcIsu.setIsuIdNum(checkInfo.getIsuSsn());
		if(checkInfo.getCustSsn() != null){
			tcIsu.setCustBirthday(DateUtil.parse(CheckIdCardUtils.getBirthByIdCard(checkInfo.getCustSsn()), DateUtil.PATTERN_CLASSICAL_SIMPLE));
		}
		tcIsu.setIsuBirthday(DateUtil.parse(CheckIdCardUtils.getBirthByIdCard(checkInfo.getIsuSsn()), DateUtil.PATTERN_CLASSICAL_SIMPLE));;
		tcIsu.setIsuSex(CheckIdCardUtils.getSexByIdCard(checkInfo.getIsuSsn()));
		tcIsu.setRelation(checkInfo.getCustShip());
		tcIsu.setEmail(checkInfo.getCustEmail());
		tcIsu.setVendor(PropertiesConfig.CAR_COMPANY_NAME);
		tcIsu.setSerialNum(2); //商业险
		
		tcIsu.setCreateUser("htbb-interface");
		tcIsu.setModifyUser("htbb-interface");
		
		tcOrderService.saveCommonOrder(tcOrder, tcIsu, null, null);
		
		if(reqOfCarIsu.getIsuDtStart() != null || !"".equals(reqOfCarIsu.getIsuDtStart())){
			//保存强险
			tcIsu.setSerialNum(1);
			tcIsu.setIsuId(String.valueOf(PropertiesConfig.iDCreator.nextId()));
			tcIsu.setDateStart(DateUtil.parse(checkInfo.getIsuDtStart(), DateUtil.PATTERN_CLASSICAL_SIMPLE));
			tcIsu.setDateEnd(DateUtil.parse(checkInfo.getIsuDtEnd(), DateUtil.PATTERN_CLASSICAL_SIMPLE));
			
			tcIsuService.save(tcIsu);
		}
		tcIsu.setIsuId(checkInfo.getIsuAid());
		return tcIsu;
	}

	/**
	 * 查询订单具体信息
	 * @param order
	 */
	public CarOrder getOrderDetail(String ordAid) {
		return tcOrderService.getCarOrderDetail(ordAid);
	}

}





